<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 响应式数据
const loading = ref(false);
const showDetailModal = ref(false);
const trendPeriod = ref('7');
const selectedRecord = ref<any>(null);

// 搜索表单
const searchForm = reactive({
  roomNumber: '',
  type: '',
  staff: '',
  dateRange: null,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

// 清洁记录数据
const records = ref([
  {
    id: '1',
    roomNumber: '101',
    type: 'regular',
    staff: '张阿姨',
    status: 'completed',
    startTime: dayjs().subtract(3, 'hour'),
    endTime: dayjs().subtract(2, 'hour'),
    duration: 1,
    quality: 4.5,
    items: [
      {
        name: '地面清洁',
        description: '清扫地面，拖地',
        completed: true,
        completedTime: dayjs().subtract(2.5, 'hour'),
      },
      {
        name: '卫生间清洁',
        description: '清洁马桶、洗手台、淋浴',
        completed: true,
        completedTime: dayjs().subtract(2.2, 'hour'),
      },
      {
        name: '厨房清洁',
        description: '清洁台面、水槽',
        completed: true,
        completedTime: dayjs().subtract(2.1, 'hour'),
      },
      {
        name: '卧室整理',
        description: '整理床铺、清洁家具',
        completed: true,
        completedTime: dayjs().subtract(2, 'hour'),
      },
    ],
    remarks: '清洁质量良好，客户满意',
    inspection: {
      inspector: '质检员A',
      time: dayjs().subtract(1.5, 'hour'),
      passed: true,
      score: 85,
      remarks: '清洁质量良好，符合标准',
    },
  },
  {
    id: '2',
    roomNumber: '201',
    type: 'checkout',
    staff: '李阿姨',
    status: 'completed',
    startTime: dayjs().subtract(6, 'hour'),
    endTime: dayjs().subtract(3, 'hour'),
    duration: 3,
    quality: 4.8,
    items: [
      {
        name: '地面深度清洁',
        description: '深度清洁地面，去除污渍',
        completed: true,
        completedTime: dayjs().subtract(4, 'hour'),
      },
      {
        name: '卫生间深度清洁',
        description: '深度清洁卫生间，消毒',
        completed: true,
        completedTime: dayjs().subtract(3.5, 'hour'),
      },
      {
        name: '厨房深度清洁',
        description: '深度清洁厨房，去除油污',
        completed: true,
        completedTime: dayjs().subtract(3.2, 'hour'),
      },
      {
        name: '家具清洁',
        description: '清洁所有家具表面',
        completed: true,
        completedTime: dayjs().subtract(3, 'hour'),
      },
    ],
    remarks: '退租清洁完成，房间焕然一新',
    inspection: {
      inspector: '质检员B',
      time: dayjs().subtract(2, 'hour'),
      passed: true,
      score: 92,
      remarks: '深度清洁质量优秀，符合退租标准',
    },
  },
  {
    id: '3',
    roomNumber: '301',
    type: 'deep',
    staff: '王阿姨',
    status: 'processing',
    startTime: dayjs().subtract(1, 'hour'),
    endTime: null,
    duration: 0,
    quality: 0,
    items: [
      {
        name: '地面抛光',
        description: '地面抛光处理',
        completed: false,
        completedTime: null,
      },
      {
        name: '卫生间消毒',
        description: '卫生间全面消毒',
        completed: false,
        completedTime: null,
      },
      {
        name: '厨房消毒',
        description: '厨房全面消毒',
        completed: false,
        completedTime: null,
      },
      {
        name: '家具保养',
        description: '家具保养护理',
        completed: false,
        completedTime: null,
      },
    ],
    remarks: '深度清洁进行中',
    inspection: null,
  },
]);

// 清洁趋势数据
const cleaningTrendData = ref([
  { date: '12-01', count: 5 },
  { date: '12-02', count: 8 },
  { date: '12-03', count: 6 },
  { date: '12-04', count: 10 },
  { date: '12-05', count: 7 },
  { date: '12-06', count: 9 },
  { date: '12-07', count: 4 },
]);

// 计算最大清洁次数
const maxCount = computed(() => {
  return Math.max(...cleaningTrendData.value.map((item) => item.count));
});

// 统计信息
const statistics = computed(() => {
  const totalCleanings = records.value.length;
  const monthlyCleanings = records.value.filter((r) =>
    dayjs(r.startTime).isSame(dayjs(), 'month'),
  ).length;
  const avgDuration =
    records.value.length > 0
      ? (
          records.value.reduce((sum, r) => sum + r.duration, 0) /
          records.value.length
        ).toFixed(1)
      : '0';
  const avgQuality =
    records.value.length > 0
      ? (
          records.value.reduce((sum, r) => sum + r.quality, 0) /
          records.value.length
        ).toFixed(1)
      : '0';

  return {
    totalCleanings,
    monthlyCleanings,
    avgDuration: `${avgDuration}h`,
    avgQuality: `${avgQuality}分`,
  };
});

// 过滤后的记录
const filteredRecords = computed(() => {
  let result = records.value;

  if (searchForm.roomNumber) {
    result = result.filter((r) => r.roomNumber.includes(searchForm.roomNumber));
  }
  if (searchForm.type) {
    result = result.filter((r) => r.type === searchForm.type);
  }
  if (searchForm.staff) {
    result = result.filter((r) => r.staff.includes(searchForm.staff));
  }
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    result = result.filter((r) => {
      const cleaningDate = dayjs(r.startTime);
      return (
        cleaningDate.isAfter(searchForm.dateRange[0]) &&
        cleaningDate.isBefore(searchForm.dateRange[1])
      );
    });
  }

  return result;
});

// 表格列定义
const columns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '清洁类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '清洁人员',
    dataIndex: 'staff',
    key: 'staff',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 150,
    customRender: ({ text }: any) => formatDateTime(text),
  },
  {
    title: '清洁时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 100,
  },
  {
    title: '质量评分',
    dataIndex: 'quality',
    key: 'quality',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 工具函数
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    regular: 'blue',
    checkout: 'orange',
    deep: 'purple',
    emergency: 'red',
  };
  return colorMap[type] || 'default';
};

const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    regular: '定期清洁',
    checkout: '退租清洁',
    deep: '深度清洁',
    emergency: '紧急清洁',
  };
  return typeMap[type] || type;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    processing: 'blue',
    completed: 'success',
    cancelled: 'default',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待开始',
    processing: '进行中',
    completed: '已完成',
    cancelled: '已取消',
  };
  return statusMap[status] || status;
};

const formatDateTime = (datetime: any) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm') : '';
  datetimedayjs.format;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  console.log('搜索条件:', searchForm);
};

const handleReset = () => {
  Object.assign(searchForm, {
    roomNumber: '',
    type: '',
    staff: '',
    dateRange: null,
  });
  pagination.current = 1;
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};

const handleViewRoom = (record: any) => {
  message.info(`查看房间：${record.roomNumber}`);
};

const handleView = (record: any) => {
  selectedRecord.value = record;
  showDetailModal.value = true;
};

const handleInspect = (record: any) => {
  message.info(`开始检查：${record.roomNumber}`);
};

const handleReinspect = (record: any) => {
  message.success(`已安排复检：${record.roomNumber}`);
};

const handleExport = () => {
  message.success('记录导出成功');
};

const handleRefresh = () => {
  message.success('数据刷新成功');
};

// 初始化
onMounted(() => {
  console.log('清洁记录追踪页面已加载');
});
</script>

<template>
  <div class="cleaning-records">
    <div class="page-header">
      <h2>清洁记录追踪</h2>
      <div class="header-actions">
        <Button @click="handleExport">
          <IconifyIcon icon="ant-design:download-outlined" />
          导出记录
        </Button>
        <Button type="primary" @click="handleRefresh">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新数据
        </Button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <Card :bordered="false" class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="房间号">
          <Input
            :value="searchForm.roomNumber"
            placeholder="请输入房间号"
            style="width: 120px"
            @input="(e) => (searchForm.roomNumber = e.target.value)"
          />
        </FormItem>
        <FormItem label="清洁类型">
          <Select
            :value="searchForm.type"
            placeholder="请选择类型"
            style="width: 140px"
            allow-clear
            @change="(value) => (searchForm.type = value)"
          >
            <SelectOption value="regular">定期清洁</SelectOption>
            <SelectOption value="checkout">退租清洁</SelectOption>
            <SelectOption value="deep">深度清洁</SelectOption>
            <SelectOption value="emergency">紧急清洁</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="清洁人员">
          <Input
            :value="searchForm.staff"
            placeholder="请输入人员"
            style="width: 120px"
            @input="(e) => (searchForm.staff = e.target.value)"
          />
        </FormItem>
        <FormItem label="清洁日期">
          <DatePicker.RangePicker
            :value="searchForm.dateRange"
            style="width: 240px"
            @change="(value) => (searchForm.dateRange = value)"
          />
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
          <Button @click="handleReset" style="margin-left: 8px">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总清洁次数"
          :value="statistics.totalCleanings"
          color="#1890ff"
          icon="ant-design:clean-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="本月清洁"
          :value="statistics.monthlyCleanings"
          color="#52c41a"
          icon="ant-design:calendar-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均时长"
          :value="statistics.avgDuration"
          color="#faad14"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="质量评分"
          :value="statistics.avgQuality"
          color="#722ed1"
          icon="ant-design:star-outlined"
        />
      </Col>
    </Row>

    <!-- 清洁趋势图 -->
    <Card :bordered="false" class="chart-card">
      <template #title>
        <span>清洁趋势</span>
        <Select
          :value="trendPeriod"
          style="width: 120px; margin-left: 16px"
          @change="(value) => (trendPeriod = value)"
        >
          <SelectOption value="7">近7天</SelectOption>
          <SelectOption value="30">近30天</SelectOption>
          <SelectOption value="90">近90天</SelectOption>
        </Select>
      </template>
      <div class="trend-chart">
        <div class="chart-item">
          <div class="chart-title">清洁次数趋势</div>
          <div class="chart-content">
            <div
              v-for="(item, index) in cleaningTrendData"
              :key="index"
              class="chart-bar"
            >
              <div class="bar-label">{{ item.date }}</div>
              <div class="bar-container">
                <div
                  class="bar-fill"
                  :style="{ height: `${(item.count / maxCount) * 100}%` }"
                ></div>
              </div>
              <div class="bar-value">{{ item.count }}</div>
            </div>
          </div>
        </div>
      </div>
    </Card>

    <!-- 清洁记录列表 -->
    <Card :bordered="false" class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredRecords"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'roomNumber'">
            <Button type="link" @click="handleViewRoom(record)">
              {{ record.roomNumber }}
            </Button>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'duration'">
            <span>{{ record.duration }}小时</span>
          </template>
          <template v-else-if="column.key === 'quality'">
            <div class="quality-info">
              <span class="quality-score">{{ record.quality }}</span>
              <div class="quality-stars">
                <IconifyIcon
                  v-for="i in 5"
                  :key="i"
                  :icon="
                    i <= record.quality
                      ? 'ant-design:star-filled'
                      : 'ant-design:star-outlined'
                  "
                  :style="{
                    color: i <= record.quality ? '#faad14' : '#d9d9d9',
                  }"
                />
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="handleInspect(record)">
                检查
              </Button>
              <Button type="link" size="small" @click="handleReinspect(record)">
                复检
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 记录详情弹窗 -->
    <Modal
      :open="showDetailModal"
      title="清洁记录详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedRecord" class="record-detail">
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-item">
                <span class="label">房间号：</span>
                <span class="value">{{ selectedRecord.roomNumber }}</span>
              </div>
              <div class="detail-item">
                <span class="label">清洁类型：</span>
                <span class="value">
                  <Tag :color="getTypeColor(selectedRecord.type)">
                    {{ getTypeText(selectedRecord.type) }}
                  </Tag>
                </span>
              </div>
              <div class="detail-item">
                <span class="label">清洁人员：</span>
                <span class="value">{{ selectedRecord.staff }}</span>
              </div>
              <div class="detail-item">
                <span class="label">清洁状态：</span>
                <span class="value">
                  <Tag :color="getStatusColor(selectedRecord.status)">
                    {{ getStatusText(selectedRecord.status) }}
                  </Tag>
                </span>
              </div>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-section">
              <h4>时间信息</h4>
              <div class="detail-item">
                <span class="label">开始时间：</span>
                <span class="value">{{
                  formatDateTime(selectedRecord.startTime)
                }}</span>
              </div>
              <div class="detail-item">
                <span class="label">结束时间：</span>
                <span class="value">{{
                  formatDateTime(selectedRecord.endTime)
                }}</span>
              </div>
              <div class="detail-item">
                <span class="label">清洁时长：</span>
                <span class="value">{{ selectedRecord.duration }}小时</span>
              </div>
              <div class="detail-item">
                <span class="label">质量评分：</span>
                <span class="value">{{ selectedRecord.quality }}分</span>
              </div>
            </div>
          </Col>
        </Row>
        <div class="detail-section">
          <h4>清洁项目</h4>
          <div class="cleaning-items">
            <div
              v-for="(item, index) in selectedRecord.items"
              :key="index"
              class="cleaning-item"
            >
              <div class="item-header">
                <span class="item-name">{{ item.name }}</span>
                <Tag :color="item.completed ? 'success' : 'default'">
                  {{ item.completed ? '已完成' : '未完成' }}
                </Tag>
              </div>
              <div class="item-desc">{{ item.description }}</div>
              <div class="item-time">
                完成时间：{{ formatDateTime(item.completedTime) }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="selectedRecord.remarks" class="detail-section">
          <h4>备注信息</h4>
          <div class="detail-item">
            <span class="value">{{ selectedRecord.remarks }}</span>
          </div>
        </div>
        <div v-if="selectedRecord.inspection" class="detail-section">
          <h4>质量检查</h4>
          <div class="inspection-info">
            <div class="detail-item">
              <span class="label">检查员：</span>
              <span class="value">{{
                selectedRecord.inspection.inspector
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">检查时间：</span>
              <span class="value">{{
                formatDateTime(selectedRecord.inspection.time)
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">检查结果：</span>
              <span class="value">
                <Tag
                  :color="
                    selectedRecord.inspection.passed ? 'success' : 'error'
                  "
                >
                  {{ selectedRecord.inspection.passed ? '通过' : '不通过' }}
                </Tag>
              </span>
            </div>
            <div class="detail-item">
              <span class="label">检查得分：</span>
              <span class="value">{{ selectedRecord.inspection.score }}分</span>
            </div>
            <div v-if="selectedRecord.inspection.remarks" class="detail-item">
              <span class="label">检查备注：</span>
              <span class="value">{{ selectedRecord.inspection.remarks }}</span>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.cleaning-records {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-card {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.chart-card {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

.trend-chart {
  padding: 16px 0;
}

.chart-item {
  margin-bottom: 24px;
}

.chart-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.chart-content {
  display: flex;
  gap: 16px;
  align-items: end;
  height: 200px;
}

.chart-bar {
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
}

.bar-label {
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.bar-container {
  position: relative;
  width: 40px;
  height: 150px;
  overflow: hidden;
  background: #f0f0f0;
  border-radius: 4px;
}

.bar-fill {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: linear-gradient(to top, #1890ff, #40a9ff);
  transition: height 0.3s ease;
}

.bar-value {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.quality-info {
  display: flex;
  gap: 8px;
  align-items: center;
}

.quality-score {
  font-weight: 600;
  color: #faad14;
}

.quality-stars {
  display: flex;
  gap: 2px;
}

.record-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin-bottom: 12px;
  font-weight: 600;
  color: #1f2937;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.detail-item .label {
  width: 100px;
  font-weight: 500;
  color: #666;
}

.detail-item .value {
  flex: 1;
  color: #1f2937;
}

.cleaning-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.cleaning-item {
  padding: 12px;
  background: #f8f9fa;
  border-left: 4px solid #1890ff;
  border-radius: 6px;
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.item-name {
  font-weight: 500;
  color: #1f2937;
}

.item-desc {
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}

.item-time {
  font-size: 12px;
  color: #999;
}

.inspection-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}
</style>
